package com.reebake.ideal.document.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.deepoove.poi.XWPFTemplate;
import com.reebake.ideal.template.util.TemplateHelper;
import lombok.SneakyThrows;
import org.jxls.builder.JxlsOutput;
import org.jxls.transform.poi.JxlsPoiTemplateFillerBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

public class RenderUtil {

    @SneakyThrows
    public static void renderExcel(InputStream is, Map<String, Object> data, OutputStream os) {
        JxlsPoiTemplateFillerBuilder.newInstance()
                .withTemplate(is)
                .build()
                .fill(data, new JxlsOutput() {
                    @Override
                    public OutputStream getOutputStream() throws IOException {
                        return os;
                    }
                });
    }

    public static void renderWord(InputStream is, Map<String, Object> data, OutputStream os){
        renderDoc(is, data, os);
    }

    @SneakyThrows
    public static void renderDoc(InputStream is, Map<String, Object> data, OutputStream os){
        XWPFTemplate template = XWPFTemplate.compile(is).render(data);
        template.write(os);
        os.flush();
        template.close();
    }

    public static String renderHtml(String source, Map<String, Object> data){
        return renderText(source, data);
    }

    private static final TemplateEngine TEMPLATE_ENGINE = TemplateUtil.createEngine();

    public static String renderText(String source, Map<String, Object> data){
        if(StrUtil.isBlank(source)){
            return source;
        }
        TemplateHelper.initStaticModels(data);
        return TEMPLATE_ENGINE.getTemplate(source).render(data);
    }
}
